/**
 *                      Copyright 2025 walter
 * <p>
 *      Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 *              http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 *      Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.walter.gitee.service;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.walter.gitee.configuration.GiteeProperties;
import com.walter.gitee.constant.RequestUrlConstant;
import com.walter.gitee.entity.EmailsEntity;
import com.walter.gitee.entity.UserEntity;
import com.walter.gitee.exceptin.GiteeException;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.util.List;

/**
 * API 相关接口
 * 参考连接：<a href="https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoSubscribers?ex=no">https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoSubscribers?ex=no</a>
 */
@Component
public class APIService {

    @Inject
    private GiteeProperties giteeProperties;

    @Inject
    private OAuthService oAuthService;

    /**
     * 获取授权用户的全部邮箱
     */
    public List<EmailsEntity> emails(String accessToken) {
        String url = String.format(RequestUrlConstant.emails_url, accessToken);
        try (HttpResponse httpResponse = HttpUtil.createGet(url).execute()) {
            if (httpResponse.getStatus() != 200) {
                throw new GiteeException("获取邮箱失败, res=" + httpResponse.body());
            }
            return JSONUtil.toList(httpResponse.body(), EmailsEntity.class);
        }
    }

    /**
     * 获取授权用户的基本信息
     */
    public UserEntity user(String accessToken) {
        String url = String.format(RequestUrlConstant.user_url, accessToken);
        try (HttpResponse httpResponse = HttpUtil.createGet(url).execute()) {
            if (httpResponse.getStatus() != 200) {
                throw new GiteeException("获取用户信息失败, res=" + httpResponse.body());
            }
            return JSONUtil.toBean(httpResponse.body(), UserEntity.class);
        }
    }
}
